package cn.txy.system.controller;

import cn.txy.config.R;
import cn.txy.system.annotation.PreAuthorize;
import cn.txy.system.domain.Menu;
import cn.txy.system.query.MenuQuery;
import cn.txy.system.service.MenuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;
    @GetMapping("/{id}")
    @PreAuthorize(name = "根据ID查询菜单",sn="menu:getOne",descs = "根据ID查询菜单")
    public R findById(@PathVariable("id")Long id){
        return R.ok(menuService.findById(id));
    }

    @GetMapping
    @PreAuthorize(name = "查询菜单",sn="menu:getAll",descs = "查询菜单")
    public R findAll(){
        return R.ok(menuService.findAll());
    }

    @DeleteMapping("/{id}")
    @PreAuthorize(name = "根据ID删除菜单",sn="menu:delOne",descs = "根据ID删除菜单")
    public R deleteById(@PathVariable("id")Long id){
        menuService.deleteById(id);
        return R.ok();
    }
    @PostMapping("/deleteAll")
    @PreAuthorize(name = "删除菜单",sn="menu:delAll",descs = "删除菜单")
    public R batchDelete(@RequestBody List<Long> ids){
        menuService.batchDelete(ids);
        return R.ok();
    }

    @ApiOperation("添加和修改")
    @PostMapping
    @PreAuthorize(name = "添加和修改菜单",sn="menu:saveOne",descs = "添加和修改菜单")
    public R add(@RequestBody Menu menu){
        if(menu.getId() == null){
            menuService.add(menu);
        }else {
            menuService.update(menu);
        }
        return R.ok();
    }
    @PostMapping("/page")
    @PreAuthorize(name = "分页查询菜单",sn="menu:page",descs = "分页查询菜单")
    public R getPage(@RequestBody MenuQuery menuQuery){
        PageHelper.startPage(menuQuery.getPage(),menuQuery.getSize());
        List<Menu> menus = menuService.queryPage(menuQuery);
        PageInfo<Menu> pageInfo = new PageInfo<>(menus);
        return R.ok(pageInfo);
    }

    @PreAuthorize(sn = "menu:menuTree",name = "菜单树",descs = "菜单树")
    @GetMapping("/menuTree")
    public R menuTree(){
        return R.ok(menuService.menuTree());
    }

}
